package com.example.filesftp.ftptransfer.util;


import com.example.filesftp.ftptransfer.domain.entity.FileTransferConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Component
public class JsonFileUtil {

    @Value("${ftp.config.file-path}")
    private String configFilePath;
    
    private final ObjectMapper objectMapper;
    
    public JsonFileUtil(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    
    public List<FileTransferConfig> readConfigs() {
        try {
            File file = new File(configFilePath);
            if (!file.exists()) {
                return Collections.emptyList();
            }
            return objectMapper.readValue(file, new TypeReference<List<FileTransferConfig>>() {});
        } catch (IOException e) {
            throw new RuntimeException("Failed to read config file", e);
        }
    }
    
    public void writeConfigs(List<FileTransferConfig> configs) {
        try {
            objectMapper.writeValue(new File(configFilePath), configs);
        } catch (IOException e) {
            throw new RuntimeException("Failed to write config file", e);
        }
    }
}